package com.iiiu.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iiiu.payment.domain.dto.PageQueryDTO;
import com.iiiu.payment.domain.dto.PaymentDTO;
import com.iiiu.payment.domain.entity.Payment;
import com.iiiu.payment.mapper.PaymentMapper;
import com.iiiu.payment.service.PaymentService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 花销记录服务实现类
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Override
    public IPage<Payment> getPaymentPage(PageQueryDTO pageQueryDTO) {
        Page<Payment> page = new Page<>(pageQueryDTO.getCurrent(), pageQueryDTO.getSize());
        
        LambdaQueryWrapper<Payment> paymentWrapper = new LambdaQueryWrapper<>();
        paymentWrapper.eq(Payment::getIsDelete, 0);
        
        // 用户ID条件
        if (pageQueryDTO.getUserId() != null) {
            paymentWrapper.eq(Payment::getUserId, pageQueryDTO.getUserId());
        }
        
        // 分类ID条件
        if (pageQueryDTO.getCategoryId() != null) {
            paymentWrapper.eq(Payment::getCategoryId, pageQueryDTO.getCategoryId());
        }
        
        // 支付方式ID条件
        if (pageQueryDTO.getPaymentMethodId() != null) {
            paymentWrapper.eq(Payment::getPaymentMethod, pageQueryDTO.getPaymentMethodId());
        }
        
        // 关键词搜索条件
        if (pageQueryDTO.getKeyword() != null && !pageQueryDTO.getKeyword().trim().isEmpty()) {
            paymentWrapper.and(wrapper -> wrapper
                .like(Payment::getDescription, pageQueryDTO.getKeyword())
                .or()
                .like(Payment::getLocation, pageQueryDTO.getKeyword())
            );
        }
        
        // 时间范围条件
        if (pageQueryDTO.getStartTime() != null) {
            paymentWrapper.ge(Payment::getCreateTime, pageQueryDTO.getStartTime());
        }
        if (pageQueryDTO.getEndTime() != null) {
            paymentWrapper.le(Payment::getCreateTime, pageQueryDTO.getEndTime());
        }
        
        // 排序
        paymentWrapper.orderByDesc(Payment::getCreateTime);
        
        return baseMapper.selectPage(page, paymentWrapper);
    }

    @Override
    public List<Payment> getByUserId(Long userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public PaymentDTO getPaymentById(Long id, Long userId) {
        Payment payment = getById(id);
        if (payment == null || !payment.getUserId().equals(userId)) {
            return null;
        }
        
        // 简化实现，直接返回Payment转换为PaymentDTO
        // 这里可以根据需要添加关联查询逻辑
        PaymentDTO dto = new PaymentDTO();
        dto.setId(payment.getId());
        dto.setPrice(payment.getPrice());
        dto.setCreateTime(payment.getCreateTime());
        dto.setUpdateTime(payment.getUpdateTime());
        dto.setUserId(payment.getUserId());
        dto.setPaymentMethod(payment.getPaymentMethod());
        dto.setCategoryId(payment.getCategoryId());
        dto.setDescription(payment.getDescription());
        dto.setLocation(payment.getLocation());
        
        return dto;
    }

    @Override
    public Payment createPayment(Payment payment) {
        // 验证必填字段
        if (payment.getPrice() == null || payment.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("金额必须大于0");
        }
        if (payment.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        if (payment.getCategoryId() == null) {
            throw new RuntimeException("分类ID不能为空");
        }
        if (payment.getPaymentMethod() == null) {
            throw new RuntimeException("支付方式ID不能为空");
        }

        payment.setIsDelete(0);
        save(payment);
        return payment;
    }

    @Override
    public Payment updatePayment(Payment payment) {
        Payment existingPayment = getById(payment.getId());
        if (existingPayment == null) {
            throw new RuntimeException("花销记录不存在");
        }

        // 检查是否属于当前用户
        if (!existingPayment.getUserId().equals(payment.getUserId())) {
            throw new RuntimeException("无权限修改此花销记录");
        }

        // 更新字段
        if (payment.getPrice() != null) {
            if (payment.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                throw new RuntimeException("金额必须大于0");
            }
            existingPayment.setPrice(payment.getPrice());
        }
        if (payment.getCategoryId() != null) {
            existingPayment.setCategoryId(payment.getCategoryId());
        }
        if (payment.getPaymentMethod() != null) {
            existingPayment.setPaymentMethod(payment.getPaymentMethod());
        }
        if (payment.getDescription() != null) {
            existingPayment.setDescription(payment.getDescription());
        }
        if (payment.getLocation() != null) {
            existingPayment.setLocation(payment.getLocation());
        }

        updateById(existingPayment);
        return existingPayment;
    }

    @Override
    public boolean deletePayment(Long id, Long userId) {
        Payment payment = getById(id);
        if (payment == null) {
            return false;
        }

        // 检查是否属于当前用户
        if (!payment.getUserId().equals(userId)) {
            throw new RuntimeException("无权限删除此花销记录");
        }

        // 软删除
        payment.setIsDelete(1);
        return updateById(payment);
    }

    @Override
    public BigDecimal getTotalAmountByUserId(Long userId) {
        LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Payment::getUserId, userId)
                   .eq(Payment::getIsDelete, 0);
        
        List<Payment> payments = list(queryWrapper);
        return payments.stream()
            .map(Payment::getPrice)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public BigDecimal getTotalAmountByCategoryId(Long userId, Long categoryId) {
        LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Payment::getUserId, userId)
                   .eq(Payment::getCategoryId, categoryId)
                   .eq(Payment::getIsDelete, 0);
        
        List<Payment> payments = list(queryWrapper);
        return payments.stream()
            .map(Payment::getPrice)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public BigDecimal getTotalAmountByPaymentMethodId(Long userId, Long paymentMethodId) {
        LambdaQueryWrapper<Payment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Payment::getUserId, userId)
                   .eq(Payment::getPaymentMethod, paymentMethodId)
                   .eq(Payment::getIsDelete, 0);
        
        List<Payment> payments = list(queryWrapper);
        return payments.stream()
            .map(Payment::getPrice)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public boolean batchDeletePayments(List<Long> ids, Long userId) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        try {
            for (Long id : ids) {
                deletePayment(id, userId);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}